import React, { useState, useEffect } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import api from '../utils/api';
import { RequestError } from '../utils/request';
import { uploadCaseImage } from '../utils/oss';
import { userStorage } from '../utils/storage';
import UploadDialog from '../components/UploadDialog';
import './CreateCase.css';

function CreateCase() {
  const navigate = useNavigate();
  const location = useLocation();
  
  const [caseTitle, setCaseTitle] = useState('');
  const [caseContent, setCaseContent] = useState('');
  const [caseType, setCaseType] = useState('emotion'); // 'emotion' | 'money' | 'study'
  const [images, setImages] = useState([]); // 存储图片文件对象和预览URL
  const [publishing, setPublishing] = useState(false);
  
  // 上传进度状态
  const [uploadDialogVisible, setUploadDialogVisible] = useState(false);
  const [currentTask, setCurrentTask] = useState('');
  const [taskProgress, setTaskProgress] = useState(0);
  const [totalTasks, setTotalTasks] = useState(0);
  const [completedTasks, setCompletedTasks] = useState(0);
  const [uploadPhase, setUploadPhase] = useState('idle'); // idle | uploading | uploaded | updating | success | error
  
  // 已上传的图片路径（用于接口重试）
  const [uploadedImagePaths, setUploadedImagePaths] = useState([]);
  const [caseDataForRetry, setCaseDataForRetry] = useState(null);

  // 当路由切换到创建案例页面时，重置表单状态
  useEffect(() => {
    if (location.pathname === '/main/create-case') {
      setCaseTitle('');
      setCaseContent('');
      setCaseType('emotion');
      setImages([]);
      setPublishing(false);
    }
  }, [location.pathname]);

  // 处理图片选择
  const handleImageSelect = (e) => {
    const files = Array.from(e.target.files);
    const remainingSlots = 9 - images.length;
    
    if (files.length > remainingSlots) {
      alert(`最多只能上传9张图片，当前已有${images.length}张，还可以上传${remainingSlots}张`);
      return;
    }

    const validImages = [];
    for (let file of files) {
      if (!file.type.startsWith('image/')) {
        alert(`${file.name} 不是图片文件，已跳过`);
        continue;
      }
      
      // 创建预览URL
      const previewUrl = URL.createObjectURL(file);
      validImages.push({
        file: file,
        previewUrl: previewUrl,
        name: file.name
      });
    }
    
    setImages([...images, ...validImages]);
    
    // 清空input，以便可以重复选择同一文件
    e.target.value = '';
  };

  // 删除图片
  const handleRemoveImage = (index) => {
    const imageToRemove = images[index];
    // 释放预览URL
    if (imageToRemove.previewUrl) {
      URL.revokeObjectURL(imageToRemove.previewUrl);
    }
    
    const newImages = images.filter((_, i) => i !== index);
    setImages(newImages);
  };

  // 处理发布
  const handlePublish = async () => {
    // 表单验证
    if (!caseTitle.trim()) {
      alert('请输入案例标题');
      return;
    }
    if (!caseContent.trim()) {
      alert('请输入案例正文');
      return;
    }
    if (images.length === 0) {
      alert('请至少上传一张图片');
      return;
    }

    setPublishing(true);
    setUploadDialogVisible(true);
    setUploadPhase('uploading');

    // 在try外部定义变量，以便在catch中使用
    let imagePaths = [];
    let imagesUploaded = false;
    let teacherPhone = '';
    let timestamp = '';

    try {
      // 1. 获取用户信息
      const userInfo = userStorage.getUserInfo();
      if (!userInfo || !userInfo.phone) {
        setUploadDialogVisible(false);
        setPublishing(false);
        alert('未获取到用户信息，请重新登录');
        navigate('/login');
        return;
      }

      teacherPhone = userInfo.phone;
      timestamp = Date.now().toString(); // 使用时间戳作为目录名

      // 2. 设置总任务数
      setTotalTasks(images.length);
      setCompletedTasks(0);

      // 3. 上传图片到OSS
      console.log('开始上传案例图片...');
      imagePaths = [];
      
      for (let i = 0; i < images.length; i++) {
        const image = images[i];
        const imageIndex = i + 1; // pic1, pic2, ...
        
        setCurrentTask(`图片 ${imageIndex} 上传中`);
        setTaskProgress(0);
        
        const ossPath = await uploadCaseImage(
          image.file,
          teacherPhone,
          timestamp,
          imageIndex,
          (progress) => {
            // progress 是 0-1 之间的值，转换为百分比
            const percentage = typeof progress === 'number' ? progress * 100 : 0;
            setTaskProgress(percentage);
            console.log(`图片 ${imageIndex} 上传进度:`, percentage + '%');
          }
        );
        imagePaths.push(ossPath);
        setCompletedTasks(i + 1);
        console.log(`图片 ${imageIndex} 上传成功:`, ossPath);
      }

      // 所有图片上传成功
      imagesUploaded = true;
      setUploadPhase('uploaded');
      setCurrentTask('图片上传完成，正在保存案例信息...');
      console.log('所有图片上传成功:', imagePaths);

      // 4. 准备案例数据
      const caseData = {
        teacherPhone: teacherPhone,
        caseTitle: caseTitle.trim(),
        caseContent: caseContent.trim(),
        caseType: caseType, // 'emotion' | 'money' | 'study'
        caseImages: imagePaths // OSS路径数组
        // 不传 _id 和 caseReadCount，后端会自动生成
      };

      // 保存数据用于重试
      setUploadedImagePaths(imagePaths);
      setCaseDataForRetry(caseData);

      setUploadPhase('updating');
      setCurrentTask('保存案例信息中...');
      console.log('准备创建案例，参数:', caseData);

      // 5. 调用创建案例接口
      const result = await api.case.addCase(caseData);

      console.log('案例创建成功:', result);

      // 6. 清理预览URL，释放内存
      images.forEach(image => {
        if (image.previewUrl) {
          URL.revokeObjectURL(image.previewUrl);
        }
      });

      setUploadPhase('success');
      setUploadDialogVisible(false);
      setPublishing(false);

      // 7. 提示成功并返回案例管理页面
      alert('案例发布成功！');
      navigate('/main/case');

    } catch (error) {
      console.error('发布案例失败:', error);
      
      // 如果图片已全部上传成功但接口调用失败，允许重试
      if (imagesUploaded && imagePaths.length > 0) {
        // 保存数据用于重试
        setUploadedImagePaths(imagePaths);
        setCaseDataForRetry({
          teacherPhone: teacherPhone,
          caseTitle: caseTitle.trim(),
          caseContent: caseContent.trim(),
          caseType: caseType,
          caseImages: imagePaths
        });
        
        setUploadPhase('error');
        if (error instanceof RequestError) {
          setCurrentTask(`保存失败: ${error.message} - 图片已上传，可以重试`);
        } else {
          setCurrentTask(`保存失败: ${error.message || '未知错误'} - 图片已上传，可以重试`);
        }
      } else {
        // 图片上传失败，关闭对话框并提示
        setUploadDialogVisible(false);
        setPublishing(false);
        if (error instanceof RequestError) {
          alert(`发布失败: ${error.message}`);
        } else {
          alert(`发布失败: ${error.message || '请重试'}`);
        }
      }
    }
  };

  // 重试保存案例信息
  const handleRetry = async () => {
    if (!caseDataForRetry) {
      alert('没有可重试的数据');
      return;
    }

    setUploadPhase('updating');
    setCurrentTask('重新保存案例信息中...');

    try {
      const result = await api.case.addCase(caseDataForRetry);
      console.log('案例创建成功:', result);

      // 清理预览URL，释放内存
      images.forEach(image => {
        if (image.previewUrl) {
          URL.revokeObjectURL(image.previewUrl);
        }
      });

      setUploadPhase('success');
      setUploadDialogVisible(false);
      setPublishing(false);

      alert('案例发布成功！');
      navigate('/main/case');

    } catch (error) {
      console.error('重试保存失败:', error);
      setUploadPhase('error');
      if (error instanceof RequestError) {
        setCurrentTask(`保存失败: ${error.message} - 可以重试`);
      } else {
        setCurrentTask(`保存失败: ${error.message || '未知错误'} - 可以重试`);
      }
    }
  };

  // 取消上传（关闭对话框）
  const handleCancelUpload = () => {
    setUploadDialogVisible(false);
    setPublishing(false);
    setUploadPhase('idle');
    // 注意：已上传的图片不会删除，用户需要手动处理
  };

  return (
    <div className="create-case-container">
      <div className="create-case-box">
        <h2>新增案例</h2>
        
        <div className="form-section">
          {/* 图片上传区域 */}
          <div className="form-group">
            <label className="required">案例图片</label>
            <div className="image-upload-grid">
              {/* 已上传的图片 */}
              {images.map((image, index) => (
                <div key={index} className="image-item">
                  <img src={image.previewUrl} alt={`预览 ${index + 1}`} />
                  <button
                    type="button"
                    className="remove-image-btn"
                    onClick={() => handleRemoveImage(index)}
                    title="删除图片"
                  >
                    ×
                  </button>
                </div>
              ))}
              
              {/* 添加图片按钮（如果未满9张） */}
              {images.length < 9 && (
                <div className="image-item add-image-item">
                  <input
                    type="file"
                    id="image-upload"
                    accept="image/*"
                    multiple
                    onChange={handleImageSelect}
                    style={{ display: 'none' }}
                  />
                  <label htmlFor="image-upload" className="add-image-btn">
                    <span className="add-icon">+</span>
                    <span className="add-text">添加图片</span>
                  </label>
                </div>
              )}
            </div>
            <div className="upload-tip">
              最多可上传9张图片，支持 JPG、PNG 格式，单张大小不超过 5MB
            </div>
          </div>

          {/* 标题输入 */}
          <div className="form-group">
            <label className="required">案例标题</label>
            <input
              type="text"
              value={caseTitle}
              onChange={(e) => setCaseTitle(e.target.value)}
              placeholder="请输入案例标题"
              maxLength="20"
            />
            <div className="char-count">
              {caseTitle.length} / 20
            </div>
          </div>

          {/* 类型选择 */}
          <div className="form-group">
            <label className="required">案例类型</label>
            <div className="radio-group">
              <label className="radio-item">
                <input
                  type="radio"
                  name="caseType"
                  value="emotion"
                  checked={caseType === 'emotion'}
                  onChange={(e) => setCaseType(e.target.value)}
                />
                <span>情感</span>
              </label>
              <label className="radio-item">
                <input
                  type="radio"
                  name="caseType"
                  value="money"
                  checked={caseType === 'money'}
                  onChange={(e) => setCaseType(e.target.value)}
                />
                <span>金钱</span>
              </label>
              <label className="radio-item">
                <input
                  type="radio"
                  name="caseType"
                  value="study"
                  checked={caseType === 'study'}
                  onChange={(e) => setCaseType(e.target.value)}
                />
                <span>学业</span>
              </label>
            </div>
          </div>

          {/* 正文输入 */}
          <div className="form-group">
            <label className="required">案例正文</label>
            <textarea
              value={caseContent}
              onChange={(e) => setCaseContent(e.target.value)}
              placeholder="请输入案例正文内容"
              rows="10"
              maxLength="5000"
            />
          </div>
        </div>
      </div>

      {/* 底部固定按钮 */}
      <div className="fixed-footer">
        <div className="footer-content">
          <button
            type="button"
            className="cancel-btn"
            onClick={() => navigate('/main/case')}
            disabled={publishing}
          >
            取消
          </button>
          <button
            type="button"
            className="publish-btn"
            onClick={handlePublish}
            disabled={publishing}
          >
            {publishing ? '发布中...' : '发布'}
          </button>
        </div>
      </div>

      {/* 上传进度对话框 */}
      <UploadDialog
        visible={uploadDialogVisible}
        currentTask={currentTask}
        progress={taskProgress}
        totalTasks={totalTasks}
        completedTasks={completedTasks}
        phase={uploadPhase}
        onRetry={handleRetry}
        onCancel={handleCancelUpload}
      />
    </div>
  );
}

export default CreateCase;

